﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace SmartKeeper
{
    public class Keeper
    {
        private readonly string _rootPath;
        private readonly EntityCache _cache;
        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="rootPath">根目录</param>
        public Keeper(string rootPath)
        {
            _rootPath = rootPath;
            _cache = new EntityCache();
        }

        public void Init()
        {
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (Type type in assembly.GetTypes())
                {
                    if (type.GetCustomAttribute<DomainAttribute>() != null)
                    {
                        PropertyData pdata = new PropertyData();
                        pdata.Reflect(_rootPath, type);
                    }
                }
            }
        }

        public T Get<T>(string id) where T:class
        {
            Type type = typeof (T);
            T t = _cache.Get<T>(type, id);
            if (t == null)
            {
                string filePath = Path.Combine(_rootPath, type.FullName, id);
                string json = File.ReadAllText(filePath);
                t = JsonConvert.DeserializeObject<T>(json);
                _cache.Set(type, id, t);
            }
            return t;
        }

        public void Save<T>(T entity)
        {

        }

        public void Update<T>(T entity)
        {

        }
    }
}
